#include <iostream>

#include <boost/process/environment.hpp>

#include "util/logger/logger.h"
#include "util/logger/logger-control.h"
#include "util/config/ui-path.h"
#include "util/config/preference-center.h"
#include "util/config/preference-entry.h"

#include "cmd-options.h"
#include "abc-server.h"


static const char *const kConfigFilePathEnvironmentVariableName = "ABC_SERVER_CONFIG_FILE_PATH";

static const PreferenceEntry<std::string> prefLogLevel("logger.level");
static const PreferenceEntry<UiPath> prefLogDir("logger.dir");
static const PreferenceEntry<std::string> prefLogBaseName("logger.basename", "abc-server-log");


static std::string getDefaultCfgFilePath() {
    const boost::process::native_environment e = boost::this_process::environment();
    const auto it = e.find(kConfigFilePathEnvironmentVariableName);
    if (it != e.end()) {
        LOGI << "default config file path found by environment variable '" << kConfigFilePathEnvironmentVariableName << "',"
            << "config file path is '" << it->to_string() << "'";
        return it->to_string();
    }

    const char *kDefaultConfigPath = "./abc-server-config.txt";
    LOGI << "default config file not found by environment variable '" << kConfigFilePathEnvironmentVariableName << "',"
        << "use config file in current directory '" << kDefaultConfigPath << "'";
    return kDefaultConfigPath;
}

int main(int argc, char *argv[]) {

    CmdOptions opts(argc, argv);
    if (opts.needHelp()) {
        opts.printHelp(std::cout);
        return 0;
    }

    // init preference
    PreferenceCenter::instance().loadCfgFileAndProcArg(getDefaultCfgFilePath(), argc, argv);

    // init logger
    logger::control::Option opt;
    opt.setLevel(*prefLogLevel);
    opt.setDir(prefLogDir->str());
    opt.setBasename(*prefLogBaseName);
    logger::control::init(opt);

    // start logic
    AbcServer server;
    server.exec();

    return 0;
}

